package com.budwk.app.sqfw.controllers.admin.customservice;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.sqfw.constants.CommonForAdminConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCommonForAdminService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.services.customservice.PovertyMonitorForAdminService;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfw.vo.SqfwShopInfoVO;
import com.budwk.app.sqfw.vo.povertymonitor.HouseHoldIncomeVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.PersonWorkDTO;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.PovertyAlleviationDTO;
import com.budwk.app.sqfwV2.enums.povertyMonitoring.FormingMaterialEnum;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @program: dfxy-community
 * @description: 扶贫监测
 * @author: LJT
 * @create: 2024-06-17 10:09
 **/
@IocBean
@At("/platform/sqfw/PovertyMonitor/")
@ApiDefinition(tag = "扶贫监测")
@Slf4j
public class PovertyMonitorForAdminController {
    @Inject(value = "PovertyMonitorForAdminService")
    private SqfwCustomForAdminCommonService sqfwCustomForAdminCommonService;

    @Inject
    private SqfwCommonForAdminService sqfwCommonForAdminService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private PovertyMonitorForAdminService povertyMonitorForAdminService;

    @At("/get/{id}")
    @Ok("json")
    @GET
    @ApiOperation(name = "获取详情")
    @ApiResponses
    @SLog(tag = "获取详情", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> detail(@Param("id") String id) {
        return Result.data(sqfwFormsummaryNewService.fetch(id));
    }

    @At("/delete")
    @Ok("json")
    @DELETE
    @ApiOperation(name = "删除表数据")
    @SLog(tag = "删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id) {
        return Result.data(sqfwCustomForAdminCommonService.delete(id));
    }

    @At("/batchDelete")
    @Ok("json")
    @DELETE
    @ApiOperation(name = "批量删除表数据")
    @SLog(tag = "批量删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> batchDelete(@Param("ids") List<String> ids) {
        return Result.data(sqfwCommonForAdminService.batchDelete(ids));
    }

    /**
     * 列表查询
     */
    @At()
    @Ok("json")
    @POST
    @ApiOperation(name = "列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "create_date", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "公共列表查询（后台管理系统）", value = "${args[0]}}")
    @SaCheckLogin
    public Result<?> list(@Param("..") SqfwCustomForAdminCommonVO bean) {
        return Result.data(sqfwCustomForAdminCommonService.list(bean));
    }

    /**
     * 获取下载文件列表及数据检查
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取下载文件列表及数据检查")
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "获取下载文件列表及数据检查", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> checkDataInfoList(@Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.checkDataInfoList(sqfwFormSummaryForAdminVO));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改")
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "修改", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> update(@Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.update(sqfwFormSummaryForAdminVO));
    }

    /**
     * excel下载
     *
     * @param sqfwFormSummaryForAdminVO
     * @return
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "Excel文件下载")
    @SLog(tag = "Excel文件下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downloadExcel(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList, @Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.downloadExcel(excelConfigList, sqfwFormSummaryForAdminVO));
    }

    /**
     * pdf下载
     *
     * @param sqfwFormSummaryForAdminVO
     * @return
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "pdf文件下载")
    @SLog(tag = "pdf文件下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downloadPdf(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList, @Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.downloadPdf(excelConfigList, sqfwFormSummaryForAdminVO));
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "重新生成PDF")
    @SaCheckLogin
    public Result<?> reGeneratePDF(@Param("sqfwFlowId") String sqfwFlowId) {
        sqfwCustomForAdminCommonService.reGeneratePdf(sqfwFlowId);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "生成材料页面")
    @SaCheckLogin
    public Result<?> generateDetailFile(@Param("..") DownExcelLedgerReqVo reqVo) {
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());
        SqlExpressionGroup sql = Cnd.exps(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName());
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getProvince())) {
            sql.and(Sqfw_formSummary_new::getProvince, "=", sysUser.getProvince());
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getCity())) {
            sql.and(Sqfw_formSummary_new::getCity, "=", sysUser.getCity());
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getDistrict())) {
            sql.and(Sqfw_formSummary_new::getDistrict, "=", sysUser.getDistrict());
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getCounty())) {
            sql.and(Sqfw_formSummary_new::getCounty, "=", sysUser.getCounty());
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getCommunity())) {
            sql.and(Sqfw_formSummary_new::getCommunity, "=", sysUser.getCommunity());
        }
        sql.and("to_char(fill_date,'YYYY-MM')", "between", new Object[]{reqVo.getFillStartDate(), reqVo.getFillEndDate()})
                .and(Sqfw_formSummary_new::getAuditStatus, "=", "submit")
                .and("param_data->>'personnelStatus'", "=", "1");
        if (StringUtils.isNotBlank(reqVo.getHouseNumber())) {
            sql.and("param_data->>'houseHoldNumber'", "=", reqVo.getHouseNumber());
        }
        List<Sqfw_formSummary_new> sqfwFormSummaryNews = sqfwFormsummaryNewService.query(Cnd.where(sql));
        boolean a = false;//县内务工
        boolean b = false;//县外务工
        for (Sqfw_formSummary_new sqfwFormSummaryNew : sqfwFormSummaryNews) {
            List<PersonWorkDTO> list = JSONUtil.toBean(sqfwFormSummaryNew.getParamData(), PovertyAlleviationDTO.class).getPersonWorkInfoList().stream()
                    .filter(s -> s.getLivingSituation().equals("1")).collect(Collectors.toList());
            if (list.size() > 0) {
                a = true;
                break;
            }
        }
        for (Sqfw_formSummary_new sqfwFormSummaryNew : sqfwFormSummaryNews) {
            List<PersonWorkDTO> list = JSONUtil.toBean(sqfwFormSummaryNew.getParamData(), PovertyAlleviationDTO.class).getPersonWorkInfoList().stream()
                    .filter(s -> s.getLivingSituation().equals("2")).collect(Collectors.toList());
            if (list.size() > 0) {
                b = true;
                break;
            }
        }

        List<CheckDataForAdminVO> checkDataForAdminVOList = new ArrayList<CheckDataForAdminVO>();
        for (FormingMaterialEnum item : FormingMaterialEnum.values()) {
            CheckDataForAdminVO checkDataForAdminVO = new CheckDataForAdminVO();
            checkDataForAdminVO.setFileIdentity(String.valueOf(item.getCode()));
            checkDataForAdminVO.setCreateConditionFlag(false);
            checkDataForAdminVO.setFileName(item.getFileName());
            if (item.getTemplat().endsWith("docx")) {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".pdf");
            } else {
                checkDataForAdminVO.setFileName(checkDataForAdminVO.getFileName() + ".xlsx");
            }
            if (CollectionUtil.isNotEmpty(sqfwFormSummaryNews) && item.getCode() >= 3) {
                checkDataForAdminVO.setCreateConditionFlag(true);
            }
            if (item.getCode() == 1 && a) {
                checkDataForAdminVO.setCreateConditionFlag(true);
            }
            if (item.getCode() == 2 && b) {
                checkDataForAdminVO.setCreateConditionFlag(true);
            }
            checkDataForAdminVOList.add(checkDataForAdminVO);
        }
        return Result.data(checkDataForAdminVOList);
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "统计家庭收入情况")
    @SaCheckLogin
    public Result<?> getHouseHoldIncome(@Param("year") String year, @Param("district") String district) {
        return Result.data(povertyMonitorForAdminService.getHouseHoldIncome(year, district));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "导入户、人数据")
    @SLog(tag = "导入户、人数据")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "houseFile", example = "1", description = "文件"),
                    @ApiFormParam(name = "personFile", example = "1", description = "文件")
            }
    )
    @AdaptBy(type = UploadAdaptor.class)
    @SaCheckLogin
    public Result<?> importHousePersonInfo(@Param("houseFile") TempFile houseFile, @Param("personFile") TempFile personFile, @Param("district") String district) {
        return Result.data(povertyMonitorForAdminService.importHousePersonInfo(houseFile, personFile, district));
    }
}
